package com.hspedu.spring.annotation2;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author： charliechou
 * @Date： 2025/11/6 10:38
 * @Describe：
 */
public class SpringContext {
    private Class springConfig;
    private ConcurrentHashMap<String, Object> ioc = new ConcurrentHashMap<>();

    public SpringContext(Class springConfig) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        this.springConfig = springConfig;
        ComponentScan componentScan =
                (ComponentScan) this.springConfig.getDeclaredAnnotation(ComponentScan.class);
        String path = componentScan.value();
        System.out.println("path: " + path);
        path = path.replace(".", "/");
        ClassLoader classLoader = this.getClass().getClassLoader();


        URL resource = classLoader.getResource(path);
        System.out.println("resource: " + resource.getPath());

        File file = new File(resource.getPath());
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for (File f : files) {
                String absolutePath = f.getAbsolutePath();
                System.out.println("absolutePath: " + absolutePath);
                String className=
                        absolutePath.substring(absolutePath.lastIndexOf("/") + 1, absolutePath.indexOf(".class"));
                System.out.println("className: " + className);
               String classFullName= path.replace("/",".")+"."+className;
                System.out.println("classFullName: " + classFullName);
                Class<?> aClass = classLoader.loadClass(classFullName);
                 if(aClass.isAnnotationPresent(Component.class)||
                         aClass.isAnnotationPresent(Controller.class)||
                         aClass.isAnnotationPresent(Service.class)||
                         aClass.isAnnotationPresent(Repository.class)){
                     Class<?> aClass1 = aClass.forName(classFullName);
                     Object instance = aClass1.newInstance();
                     ioc.put(StringUtils.uncapitalize(className),instance);
                 }




            }
        }


    }
}
